package com.zf.shuashua.advert;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.dydroid.ads.c.ADError;
import com.dydroid.ads.c.splash.SplashADListener;
import com.dydroid.ads.c.splash.SplashAdLoader;
import com.meis.base.mei.utils.Eyes;
import com.zf.shuashua.AdvertUtils;
import com.zf.shuashua.R;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.bean.AdvertReport;
import com.zf.shuashua.bean.advert.AdvertConfigBean;
import com.zf.shuashua.bean.advert.OpenConfigBean;
import com.zf.shuashua.manager.ActionThirdReportManager;
import com.zf.shuashua.utils.UIUtils;
import com.zf.shuashua.utils.Util;

public class OpenAdvertActivity extends AppCompatActivity {

    private FrameLayout mSplashContainer;
    private TextView mTvSkip;
    //开屏广告加载超时时间,建议大于3000,这里为了冷启动第一次加载到广告并且展示,示例设置了3000ms
    private static final int AD_TIME_OUT = 3500;
    private String mCodeId = "887302592";
    private String mWxId = "D1050084";
    private boolean mIsExpress = false; //是否请求模板广告
    private int count = 5;
    private MyCountDownTimer myCountDownTimer;
    private boolean canJump = false;
    private SplashAdLoader splashAdLoader;
    private int loadCount = 0;
    private boolean isDisSkip;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.bottom_in, 0);
        super.onCreate(savedInstanceState);
        Eyes.translucentStatusBar(this, true);
        setContentView(R.layout.activity_open_advert);
        initView();
        loadAdvert();
    }

    private void initView() {
        mSplashContainer = findViewById(R.id.splash_container);
        mSplashContainer.setVisibility(View.VISIBLE);
        mTvSkip = findViewById(R.id.tv_skip);
        isDisSkip = MistakeConfigManager.getInstance().isDisSkip();
    }


    private void loadAdvert(){
        OpenConfigBean openConfigBean = ShuaApplication.openConfig;
//        if(openConfigBean != null && openConfigBean.getOpen() != null && openConfigBean.getOpen().size() > 0){
//            AdvertConfigBean config = openConfigBean.getOpenConfig();
//            String codeId = config.getOrigin_id();
//            if(config.isSelf()){
//                loadSplashAd("");
//            }else if (config.isTencent()) {
//                loadSplashAd("");
//            } else {
//                loadSplashAd(codeId);
//            }
//        }else{
//            loadSplashAd("");
//        }
        loadAds();
    }

    private String uuiThirdAdvert;
    private String planId;

    private void reportRequestStart(int advert_way, String code_bit){
        ActionThirdReportManager.getInstance().reportRequestStart(advert_way, 1, code_bit, 1);
    }

    private void reportRequestSucc(int advert_way, String code_bit, int return_num) {
        ActionThirdReportManager.getInstance().reportRequestSucc(advert_way, 1, code_bit, return_num);
    }

    private void reportRequestFail(int advert_way, String code_bit, String error_code, String error_msg){
        ActionThirdReportManager.getInstance().reportRequestFail(advert_way, 1, code_bit, 1, error_code, error_msg);
    }

    private void tryLoadTencentSplash(){
//        runOnUiThread(() -> {
//            if(loadCount >= 2){
//                finish();
//            }else{
//                loadTencentSplash("");
//            }
//        });
        finish();
    }

    private void loadAds(){
        loadCount++;
        uuiThirdAdvert = Util.getUUID32();
        mSplashContainer.setVisibility(View.VISIBLE);
        mTvSkip.setVisibility(View.GONE);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT);
        params.topMargin = 70;
        params.rightMargin = 60;

        splashAdLoader = new SplashAdLoader(this, mWxId, mSplashContainer, new SplashADListener() {

            @Override
            public void onADError(ADError adError) {
                runOnUiThread(() -> {
                    if (loadCount >= 2) {
                        finish();
                    } else {
                        loadSplashAd("");
                        if (adError != null) {
                            reportRequestFail(9, mWxId, adError.getErrorCode() + "", adError.getErrorMessage() + "");
                        }
                    }
                });
            }

            @Override
            public void onADClicked() {
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, 1 + "", "9");
            }

            @Override
            public void onADShow() {
                AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, 1 + "", "9");
                reportRequestSucc(9, mWxId, 1);
            }

            @Override
            public void onADExposure() {
            }

            @Override
            public void onADDismissed() {
                next();
            }
        });
        planId = System.identityHashCode(splashAdLoader) + "";


        splashAdLoader.load();
        reportRequestStart(9, mWxId);

    }

    /**
     * 加载开屏广告
     */
    private void loadSplashAd(String codeId) {
        mCodeId = TextUtils.isEmpty(codeId) ? AdvertUtils.getSplashId() : codeId;
        loadCount++;
        uuiThirdAdvert = Util.getUUID32();
        TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(this);
        //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = null;
        //setImageAcceptedSize是px setExpressViewAcceptedSize是dp
        if (mIsExpress) {
            //个性化模板广告需要传入期望广告view的宽、高，单位dp，请传入实际需要的大小，
            //比如：广告下方拼接logo、适配刘海屏等，需要考虑实际广告大小
            float expressViewWidth = UIUtils.getScreenWidthDp(this);
            float expressViewHeight = UIUtils.getHeight(this);
            adSlot = new AdSlot.Builder()
                    .setCodeId(mCodeId)
                    .setSupportDeepLink(true)
//                    .setImageAcceptedSize(1080, 1920)
                    //模板广告需要设置期望个性化模板广告的大小,单位dp,代码位是否属于个性化模板广告，请在穿山甲平台查看
                    .setExpressViewAcceptedSize(expressViewWidth, expressViewHeight)
                    .build();
        } else {
            int expressViewWidth = UIUtils.getScreenWidthPx(this);
            int expressViewHeight = UIUtils.getScreenHeightPx(this);
            adSlot = new AdSlot.Builder()
                    .setCodeId(mCodeId)
                    .setSupportDeepLink(true)
                    .setImageAcceptedSize(expressViewWidth, expressViewHeight)
                    .build();
        }

        //step4:请求广告，调用开屏广告异步请求接口，对请求回调的广告作渲染处理
        mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
            @Override
            @MainThread
            public void onError(int code, String message) {
//                finish();
                tryLoadTencentSplash();
                reportRequestFail(1, mCodeId, code + "" , message);
            }

            @Override
            @MainThread
            public void onTimeout() {
                tryLoadTencentSplash();
//                finish();
                reportRequestFail(1, mCodeId, "408" , "time out");
            }

            @Override
            @MainThread
            public void onSplashAdLoad(TTSplashAd ad) {
                if (ad == null) {
                    tryLoadTencentSplash();
                    reportRequestSucc(1, mCodeId, 0);
                    return;
                }
                String planId = System.identityHashCode(ad) + "";
                //获取SplashView
                View view = ad.getSplashView();
                if (view != null && mSplashContainer != null && !OpenAdvertActivity.this.isFinishing()) {
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮,如果这么设置，您需要自定义倒计时逻辑
                    ad.setNotAllowSdkCountdown();
                    mSplashContainer.removeAllViews();
                    //把SplashView 添加到ViewGroup中,注意开屏广告view：width >=70%屏幕宽；height >=50%屏幕高
                    mSplashContainer.addView(view);
//                    startCountTime();
                    reportRequestSucc(1, mCodeId, 1);
                } else {
                    tryLoadTencentSplash();
                    reportRequestSucc(1, mCodeId, 0);
//                    finish();
                }

                //设置SplashView的交互监听器
                ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int type) {
//                        isAdShow = true;
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageClick, 1 + "");
                    }

                    @Override
                    public void onAdShow(View view, int type) {
                        startCountTime();
                        AdReportManager.getInstance().reportAdvertAction(uuiThirdAdvert, planId, AdvertReport.EventType.ImageShow, 1 + "");
                    }

                    @Override
                    public void onAdSkip() {
                        finish();

                    }

                    @Override
                    public void onAdTimeOver() {
                        finish();
                    }
                });
                if (ad.getInteractionType() == TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
                    ad.setDownloadListener(new TTAppDownloadListener() {
                        boolean hasShow = false;

                        @Override
                        public void onIdle() {
                        }

                        @Override
                        public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                            if (!hasShow) {
                                hasShow = true;
                            }
                        }

                        @Override
                        public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onDownloadFinished(long totalBytes, String fileName, String appName) {

                        }

                        @Override
                        public void onInstalled(String fileName, String appName) {

                        }
                    });
                }
            }
        }, AD_TIME_OUT);
        reportRequestStart(1, mCodeId);
    }

    private void startCountTime() {
        mTvSkip.setText("跳过 " + count);
        mTvSkip.setVisibility(View.VISIBLE);
        if (!isDisSkip) {
            mTvSkip.setOnClickListener(v -> {
                finish();
            });
        }
        myCountDownTimer = new MyCountDownTimer(count * 1000 + 1300, 1000);
        myCountDownTimer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myCountDownTimer != null) {
            myCountDownTimer.cancel();
            myCountDownTimer = null;
        }
        try{
            if(splashAdLoader != null){
                splashAdLoader.release();
                splashAdLoader = null;
            }
        }catch (Exception ignored){

        }
    }

    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            int count = (int)l / 1000 - 1;
            if(count < 0){
                count = 0;
            }
            if (mTvSkip != null) {
                mTvSkip.setText("跳过 " + count);
            }
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            next();
        }
    }

    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
        if (canJump) {
            finish();
        } else {
            canJump = true;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.bottom_out);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(Store.getInstance().isDisSkip()){
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
//        }
        return super.onKeyDown(keyCode, event);
    }


}
